<template>
  <div>
    <div class="container">
      <div class="handle-box">
        <el-select
          v-model="query.conferenceId"
          placeholder="请选择会议名称"
          filterable
          clearable
          style="width: 200px;" 
          class="handle-input mr10"
        >
          <el-option
            v-for="conf in conferenceData"
            :key="conf.conferenceId"
            :label="conf.conferenceName"
            :value="conf.conferenceId"
          />
        </el-select>
        <el-input v-model="query.title" clearable placeholder="直播场次标题" style="width: 200px;" class="handle-input mr10"></el-input>
        <el-select
          v-model="query.status"
          placeholder="请选择直播状态"
          clearable
          style="width: 150px;" 
          class="handle-input mr10"
        >
          <el-option label="预设/未启用" value="off"></el-option>
          <el-option label="直播中" value="running"></el-option>
          <el-option label="已结束" value="ended"></el-option>
        </el-select>
        <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        <el-button type="primary" icon="el-icon-plus" @click="addVisible = true">新增</el-button>
      </div>

      <el-table
        :data="tableData"
        border
        class="table"
        ref="multipleTable"
        header-cell-class-name="table-header"
      >
        <el-table-column label="关联会议">
          <template slot-scope="scope">
            {{ scope.row.conferences && scope.row.conferences.conferenceName || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="title" label="直播场次标题" width="180"></el-table-column>
        <el-table-column prop="streamName" label="直播流名称" width="150"></el-table-column>
        <el-table-column prop="pushUrl" label="推流URL" width="200" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-tooltip :content="scope.row.pushUrl" placement="top">
              <span>{{ scope.row.pushUrl | truncate(30) }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="playUrl" label="播流URL" width="200" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-tooltip :content="scope.row.playUrl" placement="top">
              <span>{{ scope.row.playUrl | truncate(30) }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="直播状态" width="100" align="center">
          <template slot-scope="scope">
            <el-tag 
              :type="scope.row.status === 'running' ? 'success' : scope.row.status === 'ended' ? 'info' : 'warning'"
              size="small">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="blockedParticipantTypes" label="禁止观看类型" width="150" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ formatBlockedTypes(scope.row.blockedParticipantTypes) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button
              type="text"
              icon="el-icon-edit"
              @click="handleEdit(scope.row)"
              size="small"
            >编辑</el-button>
            <el-button
              v-if="scope.row.status === 'off'"
              type="text"
              icon="el-icon-video-play"
              @click="handleStartLive(scope.row)"
              size="small"
              style="color: #67C23A;"
            >开始直播</el-button>
            <el-button
              v-if="scope.row.status === 'running'"
              type="text"
              icon="el-icon-video-pause"
              @click="handleEndLive(scope.row)"
              size="small"
              style="color: #E6A23C;"
            >结束直播</el-button>
            <el-button
              type="text"
              icon="el-icon-delete"
              class="red"
              @click="handleDelete(scope.row.liveId)"
              size="small"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="query.pageIndex"
          :page-sizes="[5, 10, 20, 30, 50]"
          :page-size="query.pageSize"
          :total="pageTotal"
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
        ></el-pagination>
      </div>
    </div>

    <!-- 编辑弹出框 -->
    <el-dialog title="编辑直播场次" :visible.sync="editVisible" width="50%">
      <el-form
        ref="editForm"
        :model="form"
        :rules="editRules"
        label-width="120px"
      >
        <el-form-item label="关联会议">
          <el-input :value="form.conferences ? form.conferences.conferenceName : ''" disabled placeholder="会议名称（不可编辑）" />
        </el-form-item>
        
        <el-form-item label="直播场次标题">
          <el-input v-model="form.title" disabled placeholder="直播场次标题（不可编辑）" />
        </el-form-item>
        
        <el-form-item label="直播流名称">
          <el-input v-model="form.streamName" disabled placeholder="直播流名称（不可编辑）" />
        </el-form-item>
        
        <el-form-item label="推流URL" prop="pushUrl">
          <el-input 
            v-model="form.pushUrl" 
            type="textarea" 
            :rows="3"
            placeholder="请输入完整的推流URL" />
        </el-form-item>
        
        <el-form-item label="播流URL" prop="playUrl">
          <el-input 
            v-model="form.playUrl" 
            type="textarea" 
            :rows="3"
            placeholder="请输入完整的播流URL" />
        </el-form-item>
        
        <el-form-item label="直播状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择直播状态" style="width: 100%;">
            <el-option label="预设/未启用" value="off"></el-option>
            <el-option label="直播中" value="running"></el-option>
            <el-option label="已结束" value="ended"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="禁止观看类型">
          <el-select
            v-model="form.blockedParticipantTypes"
            multiple
            placeholder="请选择禁止观看的参会者类型"
            style="width: 100%;"
          >
            <el-option
              v-for="type in editParticipantTypes"
              :key="type.typeId"
              :label="type.typeName"
              :value="type.typeId"
            />
          </el-select>
          <div class="form-tip">多选，选中的参会者类型将无法观看此直播</div>
        </el-form-item>
      </el-form>
    
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelEdit">取 消</el-button>
        <el-button type="primary" @click="saveEdit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 新增弹出框 -->
    <el-dialog title="新增直播场次" :visible.sync="addVisible" width="50%">
      <el-form
        ref="addForm"
        :model="addForm"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="关联会议" prop="conferenceId">
          <el-select
            v-model="addForm.conferenceId"
            placeholder="请选择会议名称"
            filterable
            clearable
            style="width: 100%;"
            @change="handleConferenceChangeAdd"
          >
            <el-option
              v-for="conf in conferenceData"
              :key="conf.conferenceId"
              :label="conf.conferenceName"
              :value="conf.conferenceId"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="直播场次标题" prop="title">
          <el-input v-model="addForm.title" placeholder="请输入直播场次标题" />
        </el-form-item>
        
        <el-form-item label="直播流名称" prop="streamName">
          <el-input v-model="addForm.streamName" placeholder="请输入直播流名称（阿里云唯一标识）" />
        </el-form-item>
        
        <el-form-item label="推流URL" prop="pushUrl">
          <el-input 
            v-model="addForm.pushUrl" 
            type="textarea" 
            :rows="3"
            placeholder="请输入完整的推流URL" />
        </el-form-item>
        
        <el-form-item label="播流URL" prop="playUrl">
          <el-input 
            v-model="addForm.playUrl" 
            type="textarea" 
            :rows="3"
            placeholder="请输入完整的播流URL" />
        </el-form-item>
        
        <el-form-item label="直播状态" prop="status">
          <el-select v-model="addForm.status" placeholder="请选择直播状态" style="width: 100%;">
            <el-option label="预设/未启用" value="off"></el-option>
            <el-option label="直播中" value="running"></el-option>
            <el-option label="已结束" value="ended"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="禁止观看类型">
          <el-select
            v-model="addForm.blockedParticipantTypes"
            multiple
            placeholder="请选择禁止观看的参会者类型"
            style="width: 100%;"
            :disabled="!addForm.conferenceId"
          >
            <el-option
              v-for="type in addParticipantTypes"
              :key="type.typeId"
              :label="type.typeName"
              :value="type.typeId"
            />
          </el-select>
          <div class="form-tip">多选，选中的参会者类型将无法观看此直播（需要先选择会议）</div>
        </el-form-item>
      </el-form>
    
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelAdd">取 消</el-button>
        <el-button type="primary" @click="saveAdd">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import requests from '../utils/request'

export default {
    name: 'LiveSessions',
    filters: {
      truncate(value, length = 30) {
        if (!value) return '';
        return value.length > length ? value.substring(0, length) + '...' : value;
      }
    },
    data() {
      return {
        query: {
            conferenceId: null,
            title: '',
            status: '',
            pageIndex: 1,
            pageSize: 30
        },
        tableData: [],
        conferenceData: [],
        participantTypes: [],
        editParticipantTypes: [], // 编辑时的参会者类型
        addParticipantTypes: [], // 新增时的参会者类型
        editVisible: false,
        addVisible: false,
        pageTotal: 0,
        form: {
          liveId: null,
          conferenceId: null,
          title: '',
          streamName: '',
          pushUrl: '',
          playUrl: '',
          status: 'off',
          blockedParticipantTypes: [],
          conferences: {
            conferenceName: ''
          }
        },
        addForm: {
          conferenceId: null,
          title: '',
          streamName: '',
          pushUrl: '',
          playUrl: '',
          status: 'off',
          blockedParticipantTypes: []
        },
        rules: {
          conferenceId: [
            { required: true, message: '请选择关联会议', trigger: 'change' }
          ],
          title: [
            { required: true, message: '请输入直播场次标题', trigger: 'blur' }
          ],
          streamName: [
            { required: true, message: '请输入直播流名称', trigger: 'blur' }
          ],
          status: [
            { required: true, message: '请选择直播状态', trigger: 'change' }
          ]
        },
        editRules: {
          status: [
            { required: true, message: '请选择直播状态', trigger: 'change' }
          ]
        }
      };
    },
    created() {
       this.loading()
    },
    methods: {
      //加载数据
      loading() {
        requests.get("/liveSessions/pageSelect", {
          page: this.query.pageIndex,
          size: this.query.pageSize,
          conferenceId: this.query.conferenceId,
          title: this.query.title,
          status: this.query.status
        }).then(res=>{
          this.pageTotal = res.total
          this.tableData = res.data
        });
        
        // 加载会议数据
        requests.get("/conferences/selectAll").then(res=>{
          this.conferenceData = res
        });
        
        // 加载参会者类型数据
        requests.get("/participantTypes/selectAll").then(res=>{
          this.participantTypes = res
        });
      },
      
      // 触发搜索按钮
      handleSearch() {
          this.query.pageIndex = 1;
          this.loading();
      },
      
      // 获取状态文本
      getStatusText(status) {
        const statusMap = {
          'off': '预设/未启用',
          'running': '直播中',
          'ended': '已结束'
        };
        return statusMap[status] || status;
      },
      
      // 格式化禁止观看类型
      formatBlockedTypes(blockedTypes) {
        if (!blockedTypes) return '-';
        const typeIds = blockedTypes.split(',').filter(id => id.trim());
        const typeNames = typeIds.map(id => {
          const type = this.participantTypes.find(t => t.typeId == id);
          return type ? type.typeName : id;
        });
        return typeNames.join(', ') || '-';
      },
      
      // 删除操作
      handleDelete(liveId) {
        this.$confirm('确定要删除这个直播场次吗？', '提示', {
            type: 'warning'
        })
        .then(() => {
            requests.delete("/liveSessions/delById", {
              liveId: liveId
            }).then(res=>{
              this.$message.success(res);
              this.loading()
            })
        })
      },
      
      // 编辑操作
      handleEdit(row) {
        const newForm = JSON.parse(JSON.stringify(row));
        
        // 确保 conferences 对象存在
        if (!newForm.conferences) {
          newForm.conferences = {
            conferenceName: ''
          };
        }
        
        // 处理禁止观看类型
        if (newForm.blockedParticipantTypes) {
          newForm.blockedParticipantTypes = newForm.blockedParticipantTypes
            .split(',')
            .filter(id => id.trim())
            .map(id => parseInt(id));
        } else {
          newForm.blockedParticipantTypes = [];
        }
        this.form = newForm;
        
        // 加载对应的参会者类型（会议ID不可编辑，直接使用现有的）
        if (this.form.conferenceId) {
          this.loadParticipantTypesByConference(this.form.conferenceId, 'edit');
        } else {
          this.editParticipantTypes = [];
        }
        
        this.editVisible = true;
      },
      
      // 取消编辑
      cancelEdit() {
        document.activeElement && document.activeElement.blur();
        this.editVisible = false;
        this.$refs.editForm.resetFields();
      },
      
      // 保存编辑
      saveEdit() {
        this.$refs.editForm.validate(valid => {
          if (!valid) {
            return;
          }
          
          // 处理禁止观看类型数据
          const formData = { ...this.form };
          if (formData.blockedParticipantTypes && formData.blockedParticipantTypes.length > 0) {
            formData.blockedParticipantTypes = formData.blockedParticipantTypes.join(',');
          } else {
            formData.blockedParticipantTypes = '';
          }
          
          requests.post("/liveSessions/edit", formData)
            .then(res => {
              this.$message.success(res);
              this.editVisible = false;
              this.loading();
            })
        });
      },
      
      // 分页导航
      handlePageChange(val) {
          this.query.pageIndex = val
          this.loading()
      },
      // 每页条数改变
      handleSizeChange(val) {
          this.query.pageSize = val
          this.loading()
      },
      

      
      // 取消新增
      cancelAdd() {
        document.activeElement && document.activeElement.blur();
        this.addVisible = false;
        this.addParticipantTypes = []; // 清空新增时的参会者类型
        this.$refs.addForm.resetFields();
      },
      
      // 保存新增
      saveAdd() {
        this.$refs.addForm.validate(valid => {
          if (!valid) {
            return;
          }
          
          // 处理禁止观看类型数据
          const formData = { ...this.addForm };
          if (formData.blockedParticipantTypes && formData.blockedParticipantTypes.length > 0) {
            formData.blockedParticipantTypes = formData.blockedParticipantTypes.join(',');
          } else {
            formData.blockedParticipantTypes = '';
          }
          
          requests.post("/liveSessions/add", formData)
            .then(res => {
              this.$message.success(res);
              this.addVisible = false;
              this.loading();
            })
        });
      },
      
      // 开始直播
      handleStartLive(row) {
        this.$confirm('确定要开始这个直播场次吗？', '提示', {
          type: 'warning'
        })
        .then(() => {
          requests.post("/liveSessions/startLive", {
            liveId: row.liveId
          }).then(res => {
            this.$message.success(res);
            this.loading();
          })
        })
      },
      
      // 结束直播
      handleEndLive(row) {
        this.$confirm('确定要结束这个直播场次吗？', '提示', {
          type: 'warning'
        })
        .then(() => {
          requests.post("/liveSessions/endLive", {
            liveId: row.liveId
          }).then(res => {
            this.$message.success(res);
            this.loading();
          })
        })
      },
      
      // 处理新增时会议变化
      handleConferenceChangeAdd(conferenceId) {
        // 清空禁止观看类型的选择
        this.addForm.blockedParticipantTypes = [];
        
        if (conferenceId) {
          this.loadParticipantTypesByConference(conferenceId, 'add');
        } else {
          this.addParticipantTypes = [];
        }
      },
      
      // 根据会议ID加载参会者类型
      loadParticipantTypesByConference(conferenceId, type) {
        requests.get("/conferenceTypeFees/selectByConferenceId", {
          conferenceId: conferenceId
        }).then(res => {
          // 从conferenceTypeFees数据中提取participantTypes信息
          const participantTypes = res.map(item => item.participantTypes).filter(Boolean);
          
          if (type === 'edit') {
            this.editParticipantTypes = participantTypes || [];
          } else if (type === 'add') {
            this.addParticipantTypes = participantTypes || [];
          }
        }).catch(err => {
          console.error('获取参会者类型失败:', err);
          if (type === 'edit') {
            this.editParticipantTypes = [];
          } else if (type === 'add') {
            this.addParticipantTypes = [];
          }
          this.$message.warning('获取参会者类型失败，请重试');
        });
      }
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.form-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 5px;
}
</style>
